package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.dto.OrderDTO;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class IOrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderLogisticsMapper orderLogisticsService;

    @Autowired
    private OrderDetailMapper orderDetailService;

    @Autowired
    ItemClient itemClient;

    @Autowired
    UserClient userClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createOrder(OrderDTO dto) {
        Order order = new Order();
        //查询商品信息
        Item item = itemClient.queryItemById(dto.getItemId());
        //基于商品商品价格，商品数量计算商品总价格
        Long totalFee = item.getPrice() * dto.getNum();
        //封装Order对象
        order.setTotalFee(totalFee);
        order.setPaymentType(dto.getPaymentType());
        order.setUserId(UserHolder.getUserId());
        order.setStatus(1);
        //存入数据库
        orderMapper.insert(order);

        //封装OrderDetail对象
        OrderDetail detail = new OrderDetail();
        detail.setName(item.getName());
        detail.setSpec(item.getSpec());
        detail.setPrice(item.getPrice());
        detail.setNum(dto.getNum());
        detail.setOrderId(order.getId());
        detail.setItemId(item.getId());
        detail.setImage(item.getImage());
        //存入数据库
        orderDetailService.insert(detail);

        //封装OrderLogistics对象
        Long addressId = dto.getAddressId();
        //根据addressId查询user服务获取地址信息
        Address address = userClient.findAddressById(addressId);
        OrderLogistics orderLogistics = new OrderLogistics();
        BeanUtils.copyProperties(address,orderLogistics);
        orderLogistics.setOrderId(order.getId());
        orderLogisticsService.insert(orderLogistics);
        //扣减库存

        return order.getId();
    }
}
